import pygame
from pygame.sprite import Sprite
from vec2d import vec2d

class ActorStatus:
    unknown = 0
    player = 1
    follow = 2
    attack = 3

# an actor is an object in the environment with goals and ambitions
class Actor(Sprite):
    def __init__(self, screen, image, init_position, init_direction):
        Sprite.__init__(self)
        self.screen = screen
        self.base_image = image
        self.image = self.base_image

        self.pos = vec2d(init_position)
        self.prev_pos = vec2d(self.pos)
        self.direction = vec2d(init_direction).normalized()

        self.target = (self.pos,self.direction)
        self.fwbw_speed = 0.0

        self.state = ActorStatus.unknown

    def follow(self,target):
        self.target = target
        self.state = ActorStatus.follow

# update the agent based on state, local environment, and goals
# the local environement is computed based on this agents state and sensing capability
# the sensing capability might just be a radius around the agent for sound or
# a conic region ahead of the agent for sight
    def update(self, local_environement, time_passed):
# this caused a memory leak
#        self.image = pygame.transform.rotate(
#            self.image, -self.direction.angle)
        if self.state == ActorStatus.follow:
            self.direction = vec2d(self.target.pos.x - self.pos.x, self.target.pos.y - self.pos.y)
            if self.direction.get_length() > 50.0:
                self.fwbw_speed = 0.001
            else:
                self.fwbw_speed = 0.0
            self.direction.normalized()

        self.image = pygame.transform.rotate(self.base_image, -self.direction.angle)

        displacement = vec2d(self.direction.x * self.fwbw_speed * time_passed,
                             self.direction.y * self.fwbw_speed * time_passed)

        self.prev_pos = vec2d(self.pos)
        self.pos += displacement

# when the image is rotated, its size is changed
        self.image_w, self.image_h = self.image.get_size()    

    def draw(self):
        self.draw_rect = self.image.get_rect().move(
            self.pos.x - self.image_w / 2,
            self.pos.y - self.image_h / 2)

        self.screen.blit(self.image, self.draw_rect)

    def forward_down(self):
#        print 'forward down'
        self.fwbw_speed = 0.05

    def forward_up(self):
#        print 'forward up'
        self.fwbw_speed = 0.0

    def backward_down(self):
        self.fwbw_speed = -0.05

    def backward_up(self):
        self.fwbw_speed = 0.0

    def left_down(self):
        self.lr_speed = 0.05

    def left_up(self):
        self.lr_speed = 0.0

    def right_down(self):
        self.lr_speed = -0.05

    def right_up(self):
        self.lr_speed = 0.0
